/*
 * @Description: 要货计划页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2021-02-23 11:12:01
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 17:00:02
 */
import React, { useCallback, useMemo } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import {
  Button,
  DataSet,
  DatePicker,
  Form,
  Modal,
  MonthPicker,
  notification,
  Output,
  Select,
  SelectBox,
  Table,
  TextField,
  Tree,
} from 'choerodon-ui/pro';
import { FuncType } from 'choerodon-ui/pro/lib/button/enum';
import { useDataSet } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  ColumnLock,
  TableAutoHeightType,
  TableColumnTooltip,
} from 'choerodon-ui/pro/lib/table/enum';
import intl from 'utils/intl';
import querystring from 'querystring';
import { NodeRenderer } from 'choerodon-ui/pro/lib/tree/util';
import {
  requireGoodsPlanDS,
  publishDS,
  areaDateSet,
  detailDS,
} from '../../stores/requireGoodsPlanDS';
import { renderSort } from '../../utils/utilsFun';
import { DataSetSelection } from 'choerodon-ui/pro/lib/data-set/enum';
import formatterCollections from 'utils/intl/formatterCollections';

const detailModalKey = Modal.key();
notification.config({
  duration: 3,
  placement: 'bottomRight',
});
interface propstype {
  dispatch: any;
}

const ClassPage: React.FC<propstype> = ({ dispatch }) => {
  const tableDS = useDataSet(() => new DataSet(requireGoodsPlanDS() as DataSetProps));
  const createDS = useDataSet(() => new DataSet(requireGoodsPlanDS() as DataSetProps));
  let areaDS = useDataSet(() => new DataSet(areaDateSet() as DataSetProps));
  const detailDateSet = useDataSet(() => new DataSet(detailDS() as DataSetProps));
  const publishMakingDS = useDataSet(() => new DataSet(publishDS() as DataSetProps));

  const handleToDetail = record => {
    const taskId = record.get('taskId');
    console.log(record.get('taskAreaId'));

    const taskAreaId = record.get('taskAreaId');
    const planMonth = record.get('taskMonth');
    const param = { taskAreaId, planMonth, taskId };
    dispatch(
      routerRedux.push({
        pathname: `/o2om/require-goods-plan-detail/${taskId}`,
        search: querystring.stringify({
          params: encodeURIComponent(JSON.stringify(param)),
        }),
      })
    );
  };

  const Columns = useMemo<any>(
    () => [
      {
        header: intl.get(`dji.otc.om.view.field.serialNumber`).d('序号'),
        width: 50,
        lock: true,
        renderer: ({ record }) => renderSort(record, tableDS),
      },
      {
        name: 'taskCode',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        lock: true,
        width: 120,
      },
      { name: 'taskDescription', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'taskMonth', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'taskStatusCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'startDate', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'endDate', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'isShowDealer', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'businessGroup', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'createdBy', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'creationDate', align: 'left', tooltip: TableColumnTooltip.always },
      {
        header: intl.get(`dji.otc.om.view.field.operationColumn`).d('操作'),
        width: 230,
        lock: ColumnLock.right,
        command: ({ record }) => {
          return [
            <Button funcType={FuncType.flat} key="edit" onClick={() => openModal('edit')}>
              {intl.get(`dji.otc.om.view.button.edit`).d('编辑')}
            </Button>,
            <Button funcType={FuncType.flat} key="look" onClick={() => openModal('look')}>
              {intl.get(`dji.otc.om.view.button.look`).d('查看')}
            </Button>,
            <Button funcType={FuncType.flat} key="import" onClick={() => handleToDetail(record)}>
              {intl.get(`dji.otc.om.view.button.importRequireGoodsDetail`).d('导入要货明细')}
            </Button>,
          ];
        },
      },
    ],
    []
  );

  // 校验是否勾选数据
  const checkSelectData = () => {
    const seletedRecord = tableDS.selected;
    if (seletedRecord.length === 0) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.remind.checkTheData`).d('请勾选操作的数据'),
      });
      return false;
    } else {
      return true;
    }
  };

  // 删除选择行
  const handleDelete = () => {
    if (checkSelectData()) {
      const seletedRecord = tableDS.selected;
      tableDS.delete(seletedRecord);
    }
  };

  // 导出模板事件
  const handleExportModel = useCallback(() => {
    dispatch(
      routerRedux.push({
        pathname: `/o2om/distribution/excel-import/O2OM_C.REQUIREMENT_TEMPLATE`,
        search: querystring.stringify({
          action: intl.get(`dji.otc.om.view.title.distributionTaskImport`).d('分货任务导入'),
          prefixPath: 'O2OM_C.REQUIREMENT_TEMPLATE',
        }),
      })
    );
  }, []);

  const publishComfirm = type => {
    if (checkSelectData()) {
      // 封装传递参数
      const seletedRecord = tableDS.selected;
      const submitData: any = [];
      seletedRecord.forEach(item => {
        submitData.push(item.data);
      });
      publishMakingDS.loadData([
        {
          djiRequirementTaskList: submitData,
          taskStatusCode: type,
        },
      ]);
      publishMakingDS.submit().then(() => {
        tableDS.query();
      });
    }
  };

  const nodeRenderer: NodeRenderer = ({ record }) => {
    return record?.get('areaName') || record?.get('largeAreaCnName');
  };

  // 编辑的时候 渲染已选数据
  const loadIntoArea = modalDS => {
    const taskId = modalDS.current?.get('taskId');
    detailDateSet.setQueryParameter('taskId', taskId);
    return detailDateSet.query().then(res => {
      const reqAreaData = res.djiRequirementTaskAreas;
      // reqAreaData.forEach(item => {
      //   const regionId = item.regionId;
      //   areaDS.forEach(record => {
      //     if (regionId === record.get('regionId')) {
      //       record.set('check', true);
      //       return
      //     }
      //   });
      // });
      const newAreaList: any = [];
      areaDS.forEach(record => {
        let checkFlag = false;
        for (const item of reqAreaData) {
          const areaId = item.areaId;
          const regionId = item.regionId;
          if (areaId === record.get('areaId') || regionId === record.get('areaId')) {
            checkFlag = true;
            break;
          }
        }
        newAreaList.push({
          ...record.data,
          check: checkFlag,
          expand: checkFlag,
        });
      });
      areaDS = new DataSet({
        primaryKey: 'keyId',
        selection: 'single' as DataSetSelection,
        paging: false,
        parentField: 'largeAreaId',
        idField: 'keyId',
        expandField: 'expand',
        checkField: 'check',
        data: newAreaList,
        transport: {
          read: config => {
            return {
              ...config,
              url: `/hitf/v1/dji-external-interface/get-regions`,
              method: 'post',
              transformResponse: value => {
                const reqData = JSON.parse(value);
                const reqareaList = reqData.data;
                const largeList: any = [];
                const areaList: any = [];
                // 去重obj
                let obj = {};

                // 去重多个小区
                let objArea = {};
                let id = 100;
                reqareaList.forEach(item => {
                  const key = item.largeAreaId;
                  if (!obj[key] && item.largeAreaId) {
                    largeList.push({
                      largeAreaCnName: item.largeAreaCnName,
                      areaId: item.largeAreaId,
                      largeAreaData: true,
                      keyId: item.largeAreaId,
                    });
                    obj[key] = key;
                  }

                  const key2 = item.areaId;
                  if (!objArea[key2]) {
                    largeList.push({
                      ...item,
                      keyId: id++,
                    });
                    objArea[key2] = key2;
                  }
                });

                const showAreaTreeList = areaList.concat(largeList);

                // const reqData = JSON.parse(value);
                // // 解决大区域没有 regionName regionId显示不了的问题
                // const newList = reqData.map(item => {
                //     return {
                //         ...item,
                //         regionName: item.regionName || item.areaName,
                //         regionId: item.regionId || item.areaId,
                //     };
                // });
                // // 按名字字母进行排序
                // newList.sort((a, b) => { return a.regionName.charCodeAt(0) - b.regionName.charCodeAt(0); });
                return showAreaTreeList;
              },
            };
          },
        },
      });
    });
  };

  const openModal = async type => {
    const modalDS = type === 'create' ? createDS : tableDS;
    let title;
    if (type === 'create') {
      title = intl.get('dji.otc.om.view.field.createRequireGoodsDetail').d('新建要货任务详情');
      modalDS.create({});
      areaDS.query();
    } else if (type === 'edit') {
      title = intl.get('dji.otc.om.view.field.editRequireGoodsDetail').d('编辑要货任务');
      await loadIntoArea(modalDS);
    } else {
      await loadIntoArea(modalDS);
      title = intl.get('dji.otc.om.view.field.lookRequireGoodsDetail').d('查看要货任务详情');
    }
    Modal.open({
      key: detailModalKey,
      title: title,
      closable: true,
      drawer: true,
      children: (
        <div>
          <Form dataSet={modalDS} disabled={type === 'look'}>
            <TextField
              name="taskCode"
              disabled
              placeholder={intl.get('dji.otc.om.view.field.generatedByTheSystem').d('系统自动生成')}
            />
            <TextField name="taskDescription" />
            <MonthPicker name="taskMonth" />
            <DatePicker name="startDate" />
            <DatePicker name="endDate" />
            <SelectBox name="isShowDealer" labelWidth={105} />
            <Select name="businessGroup" />
            <Output name="showAreaLabel" required />
          </Form>
          <Tree
            style={{ marginLeft: 100, marginTop: -36 }}
            dataSet={areaDS}
            checkable
            renderer={nodeRenderer}
            disabled={type === 'look'}
          />
        </div>
      ),
      onCancel: () => {
        modalDS.reset();
      },
      onOk: async () => {
        // 封装区域信息
        const selectRecord = areaDS.filter((item: any) => {
          return item.data.check === true && !item.data.largeAreaData;
        });
        const selectArray: any = [];
        selectRecord.forEach(record => {
          if (record.data) {
            selectArray.push({
              ...record.data,
              regionId: record.get('largeAreaId'),
            });
          }
        });
        console.log(selectArray);

        modalDS.current?.set('djiRequirementTaskAreas', selectArray);
        // 这个字段只展示 设值是为了检验能通过
        // modalDS.current?.set('showAreaLabel', '1');
        const validate = await modalDS.validate();

        if (validate) {
          handleOk(modalDS);
        } else {
          return false;
        }
      },
    });
  };

  const handleOk = modalDS => {
    modalDS.submit().then(
      res => {
        if (res) {
          tableDS.query();
        }
        modalDS.reset();
      },
      err => {
        console.log(err);
        modalDS.reset();
      }
    );
  };

  return (
    <PageHeaderWrapper
      title={intl.get('dji.otc.om.view.title.requireTask').d('要货任务')}
      header={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button onClick={() => openModal('create')}>
            {intl.get(`dji.otc.om.view.button.create`).d('新建')}
          </Button>
          <Button onClick={() => handleDelete()}>
            {intl.get(`dji.otc.om.view.button.delete`).d('删除')}
          </Button>
          <Button onClick={() => publishComfirm('published')}>
            {intl.get(`dji.otc.om.view.button.publish`).d('发布')}
          </Button>
          <Button onClick={() => publishComfirm('unpublished')}>
            {intl.get(`dji.otc.om.view.button.unpublished`).d('撤回')}
          </Button>
          <Button icon="export" key="export" onClick={() => handleExportModel()}>
            {intl.get(`dji.otc.om.view.button.improtModel`).d('导入模板')}
          </Button>
        </div>
      }
    >
      <Table
        dataSet={tableDS}
        autoHeight={{ type: TableAutoHeightType.maxHeight, diff: 80 }}
        border
        columns={Columns}
        queryFieldsLimit={3}
        // buttons={buttons}
      />
    </PageHeaderWrapper>
  );
};

export default connect()(
  formatterCollections({
    code: 'dji.otc.om',
  })(ClassPage)
);
